import requests
import json
from logger import Logger
import logging

logyyx = Logger('yyx.log', logging.ERROR, logging.DEBUG)


class qqbot:

    def __init__(self, qq, authKey, host):
        self.qq = qq
        self.authKey = authKey
        self.host = host
        self.session_num = ''
        self.headers = {
            "Content-Type": "application/json"
        }
        self.auth_verify()

    @staticmethod
    def create_message(type, message):
        return [{"type": type,
                 "text": message}]

    # 认证注册
    def auth_verify(self):
        auth_url = self.host + "/auth"
        auth_body = {
            "authKey": self.authKey
        }
        auth_body = json.dumps(auth_body)
        auth_data = requests.post(url=auth_url, data=auth_body, headers=self.headers).json()
        self.session_num = auth_data.get('session')
        verify_url = self.host + "/verify"
        verify_body = {
            "sessionKey": self.session_num,
            "qq": self.qq
        }
        verify_body = json.dumps(verify_body)
        verify_data = requests.post(url=verify_url, data=verify_body, headers=self.headers).json()
        logyyx.info('authentication result:' + verify_data.get('msg'))

    def sendFriendMessage(self, number, message):
        data = {
            "sessionKey": self.session_num,
            "target": number,
            "messageChain": self.create_message('Plain', message)
        }
        logyyx.info(number+message)
        data = json.dumps(data)
        send_url = self.host + '/sendFriendMessage'
        requests.post(url=send_url, data=data)